package cn.ac.jaas.isc.vegetable.common.security.mobile;

import cn.ac.jaas.isc.vegetable.common.security.component.VegetablePreAuthenticationChecks;
import cn.ac.jaas.isc.vegetable.common.security.service.VegetableUserDetailsService;
import cn.ac.jaas.isc.vegetable.common.security.util.VegetableSecurityMessageSourceUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsChecker;

/**
 * @author 张高昌
 * @date 2022/4/25 16:38
 * @description: 手机登录校验逻辑 验证码登录、社交登录
 */
@Slf4j
public class MobileAuthenticationProvider implements AuthenticationProvider {

    private MessageSourceAccessor messages = VegetableSecurityMessageSourceUtil.getAccessor();

    private UserDetailsChecker detailsChecker = new VegetablePreAuthenticationChecks();

    @Getter
    @Setter
    private VegetableUserDetailsService userDetailsService;



    @Override
    @SneakyThrows
    public Authentication authenticate(Authentication authentication) {
        MobileAuthenticationToken mobileAuthenticationToken = (MobileAuthenticationToken) authentication;

        String principal = mobileAuthenticationToken.getPrincipal().toString();
        String mobile = principal.substring(4);
        UserDetails userDetails = userDetailsService.loadUserByMobile(mobile);
        if (userDetails == null) {
            log.debug("Authentication failed: no credentials provided");

            throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.noopBindAccount", "Noop Bind Account"));
        }

        // 检查账号状态
        detailsChecker.check(userDetails);

        MobileAuthenticationToken authenticationToken = new MobileAuthenticationToken(userDetails, userDetails.getAuthorities());
        authenticationToken.setDetails(mobileAuthenticationToken.getDetails());
        return authenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return MobileAuthenticationToken.class.isAssignableFrom(authentication);
    }

}
